import { constantRoutes } from '@/router/router'
import { Mutation, Action } from 'vuex'
import Layout from '@/layout/Index.vue'
// eslint-disable-next-line @typescript-eslint/no-var-requires
const _import = require('@/router/_import_' + process.env.NODE_ENV)

// 遍历后台传来的路由字符串，转换为组件对象
const filterAsyncRouter = (asyncRouterMap: Array<Router>) => {
  return asyncRouterMap.filter((route: Router) => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = _import(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

export interface Meta {
  title?: string;
  icon?: string;
  noCache?: string;
  hidden?: boolean;
  alwaysShow?: boolean;
  affix?: boolean;
}

export interface Router {
  name?: string;
  path?: string;
  redirect?: string;
  component?: any;
  meta?: Meta;
  children?: Array<Router>;
}

export interface StateType {
  routes: Array<Router>;
  addRoutes: Array<Router>;
}

export interface ModuleType {
  namespaced: boolean;
  state: StateType;
  mutations: {
    SET_ROUTES: Mutation<StateType>;
  };
  actions: {
    generateRoutes: Action<StateType, StateType>;
  };
}

const storeModel: ModuleType = {
  namespaced: true,
  state: {
    routes: [],
    addRoutes: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    }
  },
  actions: {
    generateRoutes({ commit, dispatch }) {
      return new Promise((resolve, reject) => {
        dispatch('menu/getRouters', null, { root: true }).then(res => {
          const accessedRoutes = filterAsyncRouter(res.data)
          accessedRoutes.push({ path: '/:catchAll(.*)', redirect: '/', meta: { hidden: true } })
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        }).catch(err => {
          reject(err)
        })
      })
    }
  }
}
export default storeModel
